import type { PageMetaDatum, SubPageMetaDatum } from './config'
import fpath from 'node:path'
import { astToJSON5, parseConfig } from '../parse'

export async function genMainConfig(path: string) {
  const config = await parseConfig({ sources: [{ files: path }] })

  const json = config[0]
  return json
}

export function removeStartAndEnd(confStr: string) {
  return confStr.replace(/^\{/, '').replace(/\}$/, '')
}
interface IParseModule {
  pageConfigAst: any
  notFoundTip: boolean
  modulesPath: string[]
  homePagePath: string | undefined
  pageVisit?: (path: string) => void
  subPageVisit?: (arg: { fullPath: string, root: string, subPath: string }) => void
}

export async function parseModulesToJsonWithJSON5({ pageConfigAst, notFoundTip, modulesPath, homePagePath, pageVisit, subPageVisit }: IParseModule) {
  pageConfigAst = JSON.parse(JSON.stringify(pageConfigAst))
  const configList = await parseConfig({ sources: modulesPath.map(files => ({ files })) })
  const uniPageConfig = {
    pages: [] as PageMetaDatum[],
    subPackages: [] as SubPageMetaDatum[]
  }
  const pagesNode: any[] = []

  const subPagesNode: any[] = []

  for (let i = 0; i < configList.length; i++) {
    const ast = configList[i].ast as any
    if (!ast) break
    if (ast.type === 'Array') { // 未分包普通页面
      pagesParse(ast.children, i)
    }
    else if (ast.type === 'Object') { // 分包页面
      subPackagesParse(ast, i)
    }
  }

  function pagesParse(astNode: any, ind: number) {
    for (let i = 0; i < astNode.length; i++) {
      const node = astNode[i]
      const pathNode = node.children.find((e: { key: string }) => e.key === 'path')
      const path = pathNode?.value?.value

      if (homePagePath === path) {
        pagesNode.unshift(node)
        uniPageConfig.pages.unshift(configList[ind].config[i])
      }
      else {
        pagesNode.push(node)
        uniPageConfig.pages.push(configList[ind].config[i])
      }
      pageVisit && pageVisit(path)
    }
  }

  function subPackagesParse(astNode: any, ind: number) {
    subPagesNode.push(astNode)
    uniPageConfig.subPackages.push(configList[ind].config as SubPageMetaDatum)
    if (!notFoundTip) return

    const root = astNode.children.find((e: { key: string }) => e.key === 'root')?.value.value
    const subPages = astNode.children.find((e: { key: string }) => e.key === 'pages')?.value?.children
    for (let i = 0; i < subPages.length; i++) {
      const route = subPages[i]
      const pathNode = route.children.find((e: { key: string }) => e.key === 'path')
      const path = pathNode?.value?.value
      const fullPath = fpath.join(root, path)
      subPageVisit && subPageVisit({ fullPath, root, subPath: path })
    }
  }

  const includeIndex = pageConfigAst.children.findIndex((e: { key: string }) => e.key === 'include')
  if (includeIndex !== -1) {
    pageConfigAst.children.splice(includeIndex, 1)
  }

  const excludeIndex = pageConfigAst.children.findIndex((e: { key: string }) => e.key === 'exclude')
  if (excludeIndex !== -1) {
    pageConfigAst.children.splice(excludeIndex, 1)
  }

  const homePageIndex = pageConfigAst.children.findIndex((e: { key: string }) => e.key === 'homePage')
  if (homePageIndex !== -1) {
    pageConfigAst.children.splice(homePageIndex, 1)
  }

  pageConfigAst.children.unshift({
    type: 'Property',
    key: 'subPackages',
    value: {
      type: 'Array',
      children: subPagesNode
    }
  })
  pageConfigAst.children.unshift({
    type: 'Property',
    key: 'pages',
    value: {
      type: 'Array',
      children: pagesNode
    }
  })

  return { json: uniPageConfig, json5: astToJSON5(pageConfigAst) }
}
